/**
 * Created by Administrator on 2017/2/16.
 */
//创建案件公共模块
module.exports = function (caseBarService,customerBarService) {

  var newCase = {};
  var expireDate = new Date();
  expireDate.setDate(expireDate.getDate() + 1);

  //拼接JSON字符串 然后将JSON字符串作为参数传递过去
  newCase.setJson = function ($scope) {
    var j = 0;
    //如果没有选择类别 说明这个审理程序列表没有值
    if (typeof ( $scope.CaseTrialSelet) != "undefined") {
      for (var i = 0; i < $scope.CaseTrialSelet.length; i++) {
        $scope.CaseTrialSelet[i].id == $scope.mNewCase.casebusiness;
        j = i;
        break;
      }
      //$scope.mNewCase.ProcedureName = $scope.CaseTrialSelet[j].casebusinessname;
    }

    var obj = new Object();
    obj.caseTypeId = parseInt($scope.mNewCase.casetypeid);  //案件类别ID
    obj.caseClassificationId = (parseInt($scope.mNewCase.CaseClassificationId)); //案件类型ID
    obj.caseBusinessId = (parseInt($scope.mNewCase.casebusiness));//审理程序ID
    obj.caseCauseId = (parseInt($scope.mNewCase.casecauseid));    //案由ID
    obj.teamId = (parseInt($scope.mNewCase.selectedTeam));    //团队ID
    obj.caseClientType = (parseInt($scope.mNewCase.caseclienttype));    //案由ID
    //新字段
    obj.adminBody = (parseInt($scope.mNewCase.adminBody));    //行政主体
    obj.adminAct = (parseInt($scope.mNewCase.adminAct));    //行政主体
    obj.serviceType = (parseInt($scope.mNewCase.serviceType));    //业务类型
    obj.entrustType = (parseInt($scope.mNewCase.entrustType));    //委托事项
    obj.projectName = (parseInt($scope.mNewCase.projectName));    //项目名称
    obj.casesName = (parseInt($scope.mNewCase.caseName));    //项目名称
    obj.startTime = $scope.mNewCase.startTime;//开始时间
    obj.endTime = $scope.mNewCase.endTime;//结束时间
    obj.customerType = $scope.mNewCase.customerType;//客户类型：个人，企业
   // obj.customerName = $scope.mNewCase.customerName;//客户名称input
    obj.customerInfo = $scope.mNewCase.customerInfo;//客户信息是个对象
    obj.caseClient = (parseInt($scope.mNewCase.customerName)); //客户名称input
    obj.caseClientType = (parseInt($scope.mNewCase.caseClientType)); //委托人身份
    obj.handleType = (parseInt($scope.mNewCase.handleType));//案件所属


   // obj.caseClients = $scope.addPerList;  //当事人、被告、第三人数组

    //判断当事人的数组的值
    if ($scope.addPerList.length !== 0) {
      obj.caseName = $scope.addPerList[0].name + $scope.CaseAnyouModel + $scope.mNewCase.ProcedureName; //案件名称
      $scope.mmmmtxts=  obj.caseName;
    }

    obj.caseClients = $scope.addPerList;  //当事人、被告、第三人数组

    if ($scope.mNewCase.lawyersflost) {
      jsoncabe = JSON.stringify(obj);
    }
  };

  var vm = this;

  newCase.textmm = function ($scope, $rootScope,$state,$cookies) {


    $scope.validateOptions = {
      showError: false
    };
    $scope.createCaseDiv = 1;
    $scope.mNewCase.customerType = 1;
    /**定义时间*/
    var expireDate = new Date();
    expireDate.setDate(expireDate.getDate() + 1);
    /**定义客户类型*/


    /**邀请参与*/
    $scope.mInvitation=false;

    $scope.LawyerAddBodyID = {
      "position": "absolute",
      "top": "-80px",
      "width": "240px",
      "padding": "10px",
      "border": "1px solid #e0e8ec",
      "background": "#fff",
      "box-shadow": "0 2px 3px #e2e9ed",
      "margin-left": "30px",
      "left": "30px"
    };


        //案件类别选择
    $scope.caseCateTypeButton = function (ctId) {
     $("#getSS label input").removeAttr("checked");
      $('#showp').hide();
     $('#ccfid').css('width','200px');
      $scope.searchTb=ctId;
      $scope.typeId='';
      // $scope.caseform.reset()
      $scope.personalP = false;
      $scope.oneCase = true;//默认显示一个案由
      $scope.twoCases = false;//默认隐藏2个案由
      $scope.mNewCase.CaseClassificationId = "";
      $scope.mNewCase.projectName = "";//项目名称
     // $scope.mNewCase.selectedTeam = "";//选择团队
      $scope.searchName.name = "";//客户名称
        $('#pPhone').html("自动关联");
        $('#pAddr').html("自动关联");
        $('#ppAddr').html("自动关联");
      $('#cname').html("自动关联");
      $('#cphone').html("自动关联");
      $('#cAddress').html("自动关联");
      $scope.hideInde = false;
      $(".case-typeText").html("请选择"); //初始化此输入框都为空
      $(".trial-typeText").html("请选择");//初始化此输入框都为空
      $scope.CaseAnyouModel = "";
      $scope.adminBody = "";
      $scope.adminAct = "";
      $("#mMissingTest").val("");
      $("#mMissingTest2").val("");
      $("#mMissingTest3").val("");
      $scope.mNewCase.casebusiness = "";
      $scope.mNewCase.casetypeid = ctId;
      $scope.ctId = ctId;
      setmodaldata();

      setTimeout(function () {
        $('.lift10Margin').removeClass('active-show');
        $('#ctId' + ctId).addClass('active-show');
        $("#startDate").datetimepicker({
          minView: "month",
          format: 'yyyy-mm-dd',
          language: "zh-CN",
          charset: "utf-8",
        }).on('changeDate', function (ev) {
          var starTime = $('#startDate').val();
          var endTime=  $("#endDate").val();
          if(endTime!=null && endTime!=""){
            if(starTime>endTime){
              bootbox.alert({
                size: "small",
                title: "提示信息",
                message: "结束时间不能大于开始时间！",
                callback: function(){ /* your callback code */ }
              });
              $('#startDate').css('border','1px #b94a48 solid');
              return false;
            }
          }
          $('#endDate').datetimepicker('setStartDate',starTime);
          $('#startDate').datetimepicker('hide');
        });
        $("#endDate").datetimepicker({
          minView: "month",
          format: 'yyyy-mm-dd',
          language: "zh-CN",
          charset: "utf-8",
          startDate: $scope.mNewCase.startTime,
        }).on('changeDate', function (ev) {
          $('#endDate').datetimepicker('hide');
        });

      }, 100);
      $scope.litigationData();
        if(ctId==1){
          $scope.oneCase = true;//默认显示一个案由
          $scope.twoCases = false;//默认隐藏2个案由
          $('.search2').hide();
          $('.search3').hide();
          $('.search4').hide();
        }else if(ctId==2){
          $('.search1').hide();
          $('.search3').hide();
          $('.search4').hide();

        }else if(ctId==3){
          $('.search1').hide();
          $('.search2').hide();
          $('.search4').hide();
        }else if(ctId==4){
          $('.search1').hide();
          $('.search2').hide();
          $('.search3').hide();
        }

    };

    /**获取诉讼信息**/
    $scope.litigationData = function(){
      $scope.caseCateSelet = "";
      $scope.CaseTrialSelet = "";
      //清除案由
      $scope.CaseAnyouModel = "";
      $scope.adminBody = "";
      $scope.adminAct = "";
      //关闭案由下拉选框
      $scope.CaseAnyouSelet = null;
      $('#anyouUl').hide();
      $('#anyouUl1').hide();
      $('#anyouUl2').hide();
      caseBarService.getCaseType($scope.ctId).then(function (data) {
        if (data.code == 1) {
          $scope.caseCateSelet = data.data;
        }
      });
    };
    $scope.sjDiv = true;

    $scope.getTrialLevels = function(currentid){
      $('#anyouUl').hide();
      if($scope.ctId==''||$scope.ctId==undefined){
        $scope.ctId=1;
      }
      $scope.mNewCase.casebusiness = "";
      $scope.mNewCase.caseClientType = "";
      $scope.CaseAnyouModel = "";
      $scope.adminBody = "";
      $scope.adminAct = "";
      $scope.typeId = currentid;
      if(currentid!=undefined){
        caseBarService.getCaseTrial($scope.ctId, currentid).then(function (data) {
          if (data.code == 1) {
            $scope.CaseTrialSelet = data.data;
            $scope.commissionedSelect = data.data;
          }
        }, function () {
        });
      }
      $scope.oneCase = true;
      $scope.twoCases = false;
      if(currentid == 3){
        $scope.sjDiv = true;
        $('#zcDiv select').css("width","200px");
        $scope.twoCases = true;
        $scope.oneCase = false;
      }else if(currentid == 4){
        $scope.sjDiv = false;
        $('#zcDiv select').css("width","480px");
      }else{
        $scope.sjDiv = true;
        $('#zcDiv select').css("width","200px");
      }
      $("#mMissingTest").val("");
      $("#mMissingTest2").val("");
      $("#mMissingTest3").val("");
    }




    //跳过此步事件
    $scope.caseSkip = function() {
      var getCType="";
      if($scope.mNewCase.handleType==1){
        getCType="";
      }else{
        getCType = $scope.mNewCase.selectedTeam;
      }
      var newCaseObj = {
        "caseClassificationId":$scope.searchTb,//案件分组
        "caseName":$scope.mNewCase.projectName,//项目名称
        "teamId":getCType//teamid
      };
      var jsoncabe = JSON.stringify(newCaseObj);
      caseBarService.CaseSave(jsoncabe).then(function (data) {

        if(data.code == 1){
          // $rootScope.closeModal();

          $cookies.put('caseAppId', data.data.caseId, {
            expires: expireDate
          });
          $cookies.put('caseAppName', data.data.caseName, {
            expires: expireDate
          });
          $rootScope.closeModal();
          $state.go("caseBarDetailxia");
        }
      }, function () {

      });
    }
    //返回上一步
    $scope.toBack=function() {
      $scope.createCaseDiv = 1;
      $('#typeCu').hide();
    };

    var newCaseObj={};


    $scope.skipB = false;//是否显示跳过此步
    $scope.hideInde = false;//是否显示委托人身份
    $scope.identifyType = [];  //初始化委托人身份列表
    //$scope.mNewCase.customerType = 1;//默认显示案件信息页面
    $scope.oneCase = true;//是否显示2个案由
    ////是否显示选择团体
    $scope.showPer = function(){
        $scope.personalP =true;
      $scope.mNewCase.selectedTeam = "";
      caseBelongs()
    }
    //是否显示选择团体
    $scope.hidePer = function(){
      $scope.personalP =false;
      $('#showp').hide();
      $scope.mNewCase.selectedTeam = "";
    }

    //跳转到下一步
    $scope.nextStep = function(){
      $scope.showModule.searchList=false;
      if($scope.mNewCase.handleType==0){
        $('#handleType').css('border','1px #b94a48 solid');
        return;
      }
      getIdType();
      $('#serName').val('');
      $('#mMissingTest2').hide();
      var val=$('input:radio[name="chickenEgg"]:checked').val();
      // if($scope.mNewCase.customerType==''||$scope.mNewCase.customerType ==undefined){
        $scope.mNewCase.customerType = 1;
      // }else{
      //   $scope.mNewCase.customerType = $scope.mNewCase.customerType;
      // }
      $scope.natrualPerr={};
      $scope.searchName.name='';
      if($scope.searchTb==1){
        $scope.CaseAnyouModel=$('#mMissingTest').val();
        $scope.adminBody=$('#mMissingTest2').val();
        $scope.adminAct=$('#mMissingTest3').val();
        $scope.createCaseDiv = 2;
        $scope.mNewCase.caseClientType = "";
      }

      if($scope.searchTb==2){
        $scope.createCaseDiv = 2;
        setTimeout(function () {
          $("#startDate").datetimepicker({
            minView: "month",
            format: 'yyyy-mm-dd',
            language: "zh-CN",
            charset: "utf-8",
          }).on('changeDate', function (ev) {
            var startime = $('#startDate').val();
            $('#endDate').datetimepicker('setStartDate',startime);
            $('#startDate').datetimepicker('hide');
          });
          $("#endDate").datetimepicker({
            minView: "month",
            format: 'yyyy-mm-dd',
            language: "zh-CN",
            charset: "utf-8",
            startDate: $scope.mNewCase.startTime,
          }).on('changeDate', function (ev) {
            var startTime=  $("#startDate").val();
            var endTime=  $("#endDate").val();
            if(endTime>startTime){

              return false;
            }
            $('#endDate').datetimepicker('hide');
          });
        }, 100);
      }

      if($scope.searchTb==3){
        $scope.skipB = false;

        if($scope.mNewCase.startTime <= $scope.mNewCase.endTime){
          $scope.createCaseDiv = 2;
        }else{
          bootbox.alert({
            size: "small",
            title: "提示信息",
            message: "结束时间不能大于开始时间！",
            callback: function(){ /* your callback code */ }
          });
          $('#startDate').focus();
          //$('#startDate').css("border","#b94a48 1px solid");
          return;
        }
      }

      if($scope.searchTb==4){
        $scope.skipB = true;
        $scope.createCaseDiv = 2;
      }



    };


    //诉讼：根据选择项变换委托人身份
    function getIdType(){
      if($scope.searchTb ==1){
        if($scope.mNewCase.CaseClassificationId==1){
          if($scope.mNewCase.casebusiness==1){
            $scope.identifyType =customerIdentity4;
          }else if($scope.mNewCase.casebusiness==2){
            $scope.identifyType =customerIdentity2;
          }else if($scope.mNewCase.casebusiness==3){
            $scope.identifyType =customerIdentity3;
          }else{
            $scope.identifyType =customerIdentity5;
          }
        }else if($scope.mNewCase.CaseClassificationId==2){
          if($scope.mNewCase.casebusiness==1){
            $scope.identifyType =customerIdentity1;
          }else if($scope.mNewCase.casebusiness==2){
            $scope.identifyType =customerIdentity2;
          }else if($scope.mNewCase.casebusiness==3){
            $scope.identifyType =customerIdentity3;
          }else{
            $scope.identifyType =customerIdentity5;
          }
        }else if($scope.mNewCase.CaseClassificationId==3){
          if($scope.mNewCase.casebusiness==1){
            $scope.identifyType =customerIdentity1;
          }else if($scope.mNewCase.casebusiness==2){
            $scope.identifyType =customerIdentity2;
          }else if($scope.mNewCase.casebusiness==3){
            $scope.identifyType =customerIdentity3;
          }else{
            $scope.identifyType =customerIdentity5;
          }
        }else if($scope.mNewCase.CaseClassificationId==4){
            if($scope.mNewCase.casebusiness==1){
              $scope.identifyType =customerIdentity1;
            }else if($scope.mNewCase.casebusiness==2){
              $scope.identifyType =customerIdentity2;
            }else if($scope.mNewCase.casebusiness==3){
              $scope.identifyType =customerIdentity3;
            }else{
              $scope.identifyType =customerIdentity5;
            }
        }
      }else{
        $scope.identifyType =customerIdentity5;
      }
    }
//委托人身份1
    var customerIdentity1 = [
      {'id':1,'indentity':'原告'},
      {'id':2,'indentity':'被告'},
      {'id':3,'indentity':'第三人'}
    ];
    //委托人身份2
    var customerIdentity2 = [
      {'id':4,'indentity':'上诉人'},
      {'id':5,'indentity':'被上诉人'},
      {'id':6,'indentity':'第三人'}
    ];
    //委托人身份3
    var customerIdentity3 = [
      {'id':7,'indentity':'申请人'},
      {'id':8,'indentity':'被申请人'},
      {'id':9,'indentity':'第三人'}
    ];
    //委托人身份4
    var customerIdentity4 = [
      {'id':10,'indentity':'被害人'},
      {'id':11,'indentity':'自诉人'},
      {'id':12,'indentity':'犯罪嫌疑人'},
      {'id':13,'indentity':'被告人'},
      {'id':14,'indentity':'附带民事诉讼的原告人'},
      {'id':15,'indentity':'附带民事诉讼的被告人'}
    ];
    //委托人身份5
    var customerIdentity5 = [
      {'id':16,'indentity':'申请人'},
      {'id':17,'indentity':'被申请人'}
    ];


    // 点击选择一条审理程序
    $scope.trialClicked = function (trialId, trialName) {
      $scope.mNewCase.casebusiness = trialId;
      $(".trial-typeText").html(trialName);
    };


    //案由搜索列表
    $scope.CaseAnyou = function (name, keyName,event) {
      keyName = event.target.value;
      $scope.inpName = name;
      $rootScope.loadingShow = true;
      $rootScope.fadeShow = true;
      /**案由*/
      caseBarService.CaseAnyou($scope.typeId, keyName).then(function (data) {
        if (data.code == 1) {
          if ($scope.typeId != 3){
            $scope.CaseAnyouSelet = data.data;
            if( $scope.CaseAnyouSelet!=null){
              $('#anyouUl').show();
            }else{
              $('#anyouUl').hide();
            }

          }
        }
       $rootScope.loadingShow = false;
       $rootScope.fadeShow = false;
      }, function () {
       $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
      });
    };
    $scope.CaseAnyouZY = function (keyID, keyName,event) {
      $scope.inpName = keyID;
      if(keyID==1){
        $('#anyouUl3').hide();
      }else if(keyID==2){
        $('#anyouUl2').hide();
      }
      $rootScope.loadingShow = true;
      $rootScope.fadeShow = true;
      keyName = event.target.value;
      /**案由*/
      caseBarService.CaseAnyou($scope.typeId, keyName, keyID).then(function (data) {
        if (data.code == 1) {
          if(keyID==1){
            $scope.CaseAnyouSelet = data.data;
              if($scope.CaseAnyouSelet!=null){
                $('#anyouUl2').show();
              }else{
                $('#anyouUl2').hide();
              }

          }else if(keyID==2){
            $scope.CaseAnyouSelet = data.data;
            if($scope.CaseAnyouSelet!=null){
              $('#anyouUl3').show();
            }else{
              $('#anyouUl3').hide();
            }

          }
        }
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
      }, function () {
        $rootScope.loadingShow = false;
        $rootScope.fadeShow = false;
      });
    };


    //点击列表中的复选框.
    $scope.CaseAnyouRadio = function (value, id ,$event) {
      $scope.mNewCase.casecauseid = id;
      /**angular作用域失效，没办法在这里附上值*/
      $("#mMissingTest").val(value);
      $scope.CaseAnyouModel = value;
      if($scope.inpName == 1){
        $("#mMissingTest2").val(value);
        $scope.mNewCase.adminBody=id;
        $scope.adminBody=value;
      }else if($scope.inpName == 2){
        $("#mMissingTest3").val(value);
        $scope.mNewCase.adminAct = id;
        $scope.adminAct = value;
      }
      $('#anyouUl').hide();
      $('#anyouUl2').hide();
      $('#anyouUl3').hide();
    };

    var watchSearName = $scope.$watch('searchName.name',function(newValue,oldValue, scope){
      $('#serName').css('border','1px #ccc solid');
    }, true);
    var watchstartTime = $scope.$watch('mNewCase.startTime',function(newValue,oldValue, scope){
      $('#startDate').css('border','1px #ccc solid');
    }, true);
   $scope.$watch('mNewCase.handleType',function(newValue,oldValue, scope){
      $('#handleType').css('border','0px #ccc solid');
    }, true);



    $rootScope.closeModal = function(){
      // $('#myModal2').hide();

      $("#myModal21").animate({top:-($("#myModal21").height()+50)+'px'});

       setmodaldata();

      // $scope.selectInfo(1, $scope.biglawuserid, "1", "10");
      //  if($state.current.url == '/caseBar'){
      //    console.log($state.current.url)
      //    $scope.selectInfo(1, $scope.biglawuserid, "1", "10");
      //  }

    }
    // $scope.$watch('closeModal',function(){
    //   $scope.selectInfo(1, $scope.biglawuserid, "1", "10");
    // },true);

    //保存案件
    $scope.saveCase = function(){
      var searchN = $('#serName').val();
      if($scope.searchTb==1){
        var addPersonItem = [];
        addPersonItem.push($scope.addPerList[$scope.addPerList.length-1]);
        var getCType="",  sjP = "", anyouId= "",anyouAct = "";
        if($scope.mNewCase.handleType==1){
          getCType="";
        }else{
          getCType = $scope.mNewCase.selectedTeam;
        }
        if($scope.mNewCase.CaseClassificationId==3){
          anyouId = $scope.mNewCase.adminBody;
          anyouAct= $scope.mNewCase.adminAct
        }else{
          anyouId = $scope.mNewCase.casecauseid;
          anyouAct="";
        }

        if($scope.mNewCase.CaseClassificationId==4){
          sjP="";
        }else{
          sjP=$scope.mNewCase.casebusiness;
        }
        //判断行政
        var newCaseObj = {
          "caseClassificationId":$scope.searchTb,//案件分组
          "caseTypeId":$scope.mNewCase.CaseClassificationId,//案件类型
          "caseBusinessId":sjP,//审级
          "caseCauseId":anyouId,//案由或者行政主体
          "caseCauseActionId":anyouAct,//行政行为
          "teamId":getCType,//teamID
          "caseClients":addPersonItem,//客户名称
          "caseClientType":$scope.mNewCase.caseClientType//委托人身份
        };

        var jsoncabe = JSON.stringify(newCaseObj);
      };

      if($scope.searchTb==2){
        var addPersonItem = [];
        addPersonItem.push($scope.addPerList[$scope.addPerList.length-1]);
        var getCType="";
        if($scope.mNewCase.handleType==1){
          getCType="";
        }else{
          getCType = $scope.mNewCase.selectedTeam;
        };
        var newCaseObj = {
          "caseClassificationId":$scope.searchTb,//案件分组
          "caseBusinessTypeId":$scope.mNewCase.serviceType,//业务类型
          "entrustedBusinessId":$scope.mNewCase.entrustType,//委托事项
          "caseName":$scope.mNewCase.caseName,//项目名称
          "teamId":getCType,//teamID
          "caseClients":addPersonItem//客户名称
        };
        var jsoncabe = JSON.stringify(newCaseObj);


      };

      if($scope.searchTb==3){
        var addPersonItem = [];
        addPersonItem.push($scope.addPerList[$scope.addPerList.length-1]);
        var getCType="";
        if($scope.mNewCase.handleType==1){
          getCType="";
        }else{
          getCType = $scope.mNewCase.selectedTeam;
        }
        var newCaseObj = {
          "caseClassificationId":$scope.searchTb,//案件分组
          "caseBusinessTypeId":$scope.mNewCase.serviceType,//业务类型
          "contractStartDate":$scope.mNewCase.startTime,//开始时间
          "contractEndDate":$scope.mNewCase.endTime,//结束时间
          "teamId":getCType,//teamid
          "caseClients":addPersonItem//客户名称
        };
        var jsoncabe = JSON.stringify(newCaseObj);
      };

      if(searchN != null && searchN!=""){
        $('#serName').css('border','1px #ccc solid');
        caseBarService.CaseSave(jsoncabe).then(function (data) {
          if(data.code == 1){
            // $rootScope.closeModal();

            $cookies.put('caseAppId', data.data.caseId, {
              expires: expireDate
            });
            $cookies.put('caseAppName', data.data.caseName, {
              expires: expireDate
            });
            $('#myModal2').hide();
            $state.go("caseBarDetailxia");
          }else{
            $('#serName').css('border','1px #b94a48 solid');
            return false;
          }
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
        }, function () {
          $rootScope.loadingShow = false;
          $rootScope.fadeShow = false;
        });
      }else{
        $('#serName').css('border','1px #b94a48 solid');
        return false;
      }

      if($scope.searchTb==4){
        var addPersonItem = [];
        addPersonItem.push($scope.addPerList[$scope.addPerList.length-1]);
        var getCType="";
        if($scope.mNewCase.handleType==1){
          getCType="";
        }else{
          getCType = $scope.mNewCase.selectedTeam;
        }
        if(searchN ==""){
          $("#cname").addClass('writeError');
           return false;
        }else{
          $("#cname").removeClass('writeError');
          var  newCaseObj = {
            "caseClassificationId":$scope.searchTb,//案件分组
            "caseName":$scope.mNewCase.projectName,//项目名称
            "teamId":getCType,//teamid
            "caseClients":addPersonItem//客户名称
          };
          var jsoncabe = JSON.stringify(newCaseObj);
          caseBarService.CaseSave(jsoncabe).then(function (data) {
            if(data.code == 1){
              // $rootScope.closeModal();
              $cookies.put('caseAppId', data.data.caseId, {
                expires: expireDate
              });
              $cookies.put('caseAppName', data.data.caseName, {
                expires: expireDate
              });
              $rootScope.closeModal();
              $state.go("caseBarDetailxia");

            }
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
          }, function () {
            $rootScope.loadingShow = false;
            $rootScope.fadeShow = false;
          });
        }


      }
      $rootScope.typeIf = 1;
      $cookies.put('type', $rootScope.typeIf, {//已归档和处理中类型
        expires: expireDate

      });
    }

    //保存时 清空里面的值
    function setmodaldata() {
      $scope.mNewCase={
        casetypeid:'',
        CaseClassificationId:'',
        casebusiness:'',
        casecauseid:'',
        caseClient:'',//委托人身份
        handleType:'',//案件所属
        projectName:'',//项目名称
        caseName:'',
        serviceType:'',//业务类型
        startTime:'',//开始时间
        endTime:'',//结束日期
        entrustType:'',//委托事项
        UserType:1,
        strcaseType:3
      }
      // $scope.mNewCase.UserType = 1;
      // $scope.mNewCase.strcaseType = 3;
      // $scope.mNewCase.casetypeid = "";
      // $scope.mNewCase.CaseClassificationId = '';
      // $scope.mNewCase.casebusiness = "";
      // $scope.mNewCase.casecauseid = "";

      //$scope.mNewCase.customerName=""; //客户名称
      // $scope.mNewCase.caseClient="";//委托人身份
      // $scope.mNewCase.handleType="";//案件所属
      // $scope.mNewCase.projectName="";//项目名称

      // $scope.mNewCase.serviceType = "";//业务类型
      // $scope.mNewCase.startTime = "";//开始时间
      // $scope.mNewCase.endTime = "";//结束日期
      // $scope.mNewCase.entrustType=""//委托事项
      // $scope.mNewCase.caseName = "";
     // $scope.addPerList = null;
      //$(".case-typeText").html("请选择");
      //$(".trial-typeText").html("请选择");

      $scope.searchName.name = "";//客户名称搜索框
      $scope.mMatterPerson.adversaryClients = [];
      $scope.mMatterPerson.Consignor = [];

      $scope.CaseAnyouModel = "";//案由
      $scope.adminBody = "";//行政主体
      $scope.adminAct = "";//行政行为

      $scope.CaseAnyouModel = ""

      //主办
      $scope.cacaName = $scope.mSponsor;
      //案源
      $scope.mCaseSource = undefined;
    }


    //添加委托人
    $scope.showModule = {
      naturalPer:false,
      organiza:false,
      showPerInput:true,
      showOrganizaInput:false,
      searchList:false,//自然人搜索
      searchOrgList:false,//机构搜索
      addModule:false,
      createPer:false,
      createOrganiza:false,
      addClose:false,
      searchRe:false
    };
    $scope.caseBarOrganiza = caseBarOrganiza;
    $scope.caseBarNaturalPer = caseBarNaturalPer;
    //$scope.addNewPer = addNewPer;
    //$scope.addNewOrganiza = addNewOrganiza;
    $scope.createNewPer = createNewPer;
    $scope.createNewOrganiza = createNewOrganiza;
    $scope.NaturalPerOpen = NaturalPerOpen;
    $scope.OrganizaOpen = OrganizaOpen;
    //$scope.savePer = savePer;
    //$scope.saveOrganiza = saveOrganiza;
    $scope.caseBelongs = caseBelongs;
    $scope.selectConsigner = selectConsigner;
    //$scope.selectAnyou = selectAnyou;


    $scope.searchName = {};
    $scope.searchOrganizaName = {};
    $scope.addNaturalPer = {};
    $scope.addOrganiza = {};
    $scope.mNewCase.selectedTeam = "";

    $scope.addPerList = [];

    function init() {
      // NaturalPerOpen();
      caseBelongs();

    }
    init();
    //案件所属
    function caseBelongs() {
      customerBarService.caseBelongs().then(function (response) {
        $scope.teamList = response.data.data;
      })
    };

    //默认打开自然人的搜索
    function NaturalPerOpen() {
      $scope.showModule.addModule = true;
      $scope.showModule.showPerInput = true;
      $scope.showModule.showOrganizaInput = false;
      $scope.showModule.naturalPer = false;
      $scope.showModule.organiza = false;
      $scope.showModule.createPer = false;
      $('.NaturalPerOpen').addClass('L_active');
      $('.OrganizaOpen').removeClass('L_active');
      $scope.addNaturalPer = {};
    }
    //打开机构的搜索
    function OrganizaOpen() {
      $scope.showModule.addModule = true;
      $scope.showModule.showOrganizaInput = true;
      $scope.showModule.showPerInput = false;
      $scope.showModule.naturalPer = false;
      $scope.showModule.organiza = false;
      $scope.showModule.createPer = false;
      $('.NaturalPerOpen').removeClass('L_active');
      $('.OrganizaOpen').addClass('L_active');
    }

$scope.showPersonResult=function(){
      if($scope.searchName.name==''){
        $('#PromptD').css('display','none');
      }else{
        if($scope.mNewCase.customerType==1){
          caseBarNaturalPer();
        }else if($scope.mNewCase.customerType==2){
          caseBarOrganiza();
        }
      }


}
//小提示


$scope.showPersonResultHide=function(){
 $scope.showModule.searchList=true;

}
    //查询个人客户信息
    function caseBarNaturalPer() {
      var params = {'customerName':$scope.searchName.name};
      customerBarService.searchPersonCustomer(params).then(function (response) {
        if(response.data.code == 1){
          if(response.data.data==null){
            $scope.showModule.searchList = false;
           /* bootbox.alert({
              size: "small",
              title: "提示信息",
              message: '该客户不存在，请创建新客户',
              callback: function(){ /!* your callback code *!/ }
            });*/
           $('#PromptD').css('display','block');

            $('#pPhone').html();
            $('#pAddr').html();
            $('#ppAddr').html();
          }else{
            $('#PromptD').css('display','none');
            $scope.searchNaturalPerList = response.data.data;
            if($scope.searchNaturalPerList != null){
              $scope.showModule.searchList = true;
              // $scope.showModule.createPer = false;
            }else if($scope.searchNaturalPerList == null) {
              $scope.showModule.searchList = false;
              //$scope.showModule.createPer = true;
            }
          }
        }else{
          $scope.showModule.searchList = false;
        }
      });
    }
    //查询企业信息
    function caseBarOrganiza() {
      var params = {'customerName':$scope.searchName.name};
      customerBarService.searchCustomerCustomer(params).then(function (response) {
        if(response.data.code == 1){
          $scope.searchNaturalPerList = response.data.data;
          if($scope.searchNaturalPerList != ''){

            $('#PromptD').css('display','none');
            $scope.showModule.searchList = true;
          }else{
            $('#PromptD').css('display','block');
            $('#cname').html();
            $('#cphone').html();
            $('#cAddress').html();
            $scope.showModule.searchList = false;
          }
        }
      });
    }
    //从列表选择委托人并赋值给下面的字段
    function selectConsigner(natrualPer, type) {
      if (natrualPer == null) {
        return;
      }
      var flag = false;
      for(var i=0;i<$scope.addPerList.length; i++){
        if ($scope.addPerList[i].id == natrualPer.customerpersonId || $scope.addPerList[i].id == natrualPer.customercompanyId) {
          flag = true;
        }
      }
      var item = {
        id: natrualPer.customerpersonId || natrualPer.customercompanyId,
        name: natrualPer.name,
        type : type
      };
      if(!flag){
        // if($scope.addPerList.length<1){
        //   $scope.addPerList[0].push(item);
        // }
        $scope.addPerList.push(item);
      }
      $scope.natrualPerr=natrualPer
      $scope.searchName.name = natrualPer.name;
      if($scope.mNewCase.customerType==1){
        $('#pPhone').html(natrualPer.phone);
        $('#pAddr').html(natrualPer.address || '无');
        $('#ppAddr').html(natrualPer.workPlace || '无');
      }else if($scope.mNewCase.customerType==2){
        $('#cname').html(natrualPer.contactName);
        $('#cphone').html(natrualPer.phone || '无');
        $('#cAddress').html(natrualPer.address || '无' );
      }
      $scope.showModule.searchList = false;
    }


/*
    //添加新的自然人
    function addNewPer() {
      $scope.showModule.addModule = true;
      NaturalPerOpen();
    }
    //添加新的机构
    function addNewOrganiza() {
      $scope.showModule.addModule = true;
      OrganizaOpen();
    }
*/
    //创建个人客户
    function createNewPer() {
      $scope.paramsP={};
      $scope.paramsM={};
      $scope.paramsM.contactphone=''
      $scope.paramsP.contactnumber='';
      $scope.showModule.searchList = false;
      $('#addPerson').modal('show');
      if($scope.mNewCase.customerType==1){

        $scope.personActive = 0;
        $('#companyD').hide();
        $('#personD').show();
      }else if($scope.mNewCase.customerType==2){
        $scope.personActive = 1;
        // $('#companyD').hide();
        // $('#personD').hide();
      }
      $('#PromptD').css('display','none');
    }

    //创建新的机构
    function createNewOrganiza() {
      $scope.showModule.organiza = true;
      $scope.showModule.naturalPer = false;
      $scope.showModule.showPerInput = false;
      $scope.showModule.showOrganizaInput = false;
      $scope.showModule.createPer = false;
    }
/*
    //保存自然人
    function savePer(addNaturalPer) {
      if($scope.phoneEmpty){
        return;
      }else if($scope.phoneValid){
        return;
      }
      customerBarService.addZRRCustomer(addNaturalPer).then(function (data) {
        //$scope.showModule.addModule = false;
        if(data.code == 1){
         // console.log(data)
          $('#addPerson').modal('hide');
          var item = {
            name:addNaturalPer.name,
            id:data.data,
            type:1
          };
          $scope.addPerList.push(item);
          $('.L_peplAddBox2').css('display','none');
          $scope.addNaturalPer = {};
        }
      });
    }

    //保存机构
    function saveOrganiza(addOrganiza) {
      customerBarService.addFRCustomer(addOrganiza).then(function (data) {
        $scope.showModule.addModule = false;
        var item = {
          id:data.data,
          type:2,
          name:addOrganiza.companyname
        };
        $scope.addPerList.push(item);
        $scope.addOrganiza = {};
      })
    }
*/
$scope.getCusType = function(customerType){
  $scope.natrualPerr={}
  if(customerType==1){
    $scope.showModule.searchList = false;
    //$scope.searchName.name = "";
    //$('#serName').val('');
    $scope.mNewCase.customerType=1;
  }else{
    $scope.mNewCase.customerType=2;
   // $scope.searchName.name = "";
    $('#serName').val('');
    $scope.showModule.searchList= false;
  }

}



/******************添加客户事件******************************/

    //添加客户弹框
    //自然人法人切换显示
    $scope.tabShow = 0;
    $scope.getPersonListGroup = getPersonListGroup;
    $scope.personActive = 0;
    $scope.teamSelected = 1;
    $scope.showTeam = showTeam;
    showTeam(-6);
    function showTeam(index) {
      $scope.teamSelected = index;
    };
    //客户左侧列表显示

    getPersonListGroup();
    function getPersonListGroup() {
      customerBarService.getPersonListGroup().then(function (response) {
        if(response.data.code == 1){
          $scope.customerList = response.data.data;
          $scope.listActive = $scope.customerList[0].customerGroupId;
          $scope.customerListNum = response.data.totalCount;

         // $scope.selectZiRanRenInfo();
          $scope.groupName = response.data.data[0].customerGroupName;
        }
      });
    };
    /*新增用户*/
    //新增自然人机构用户
    $scope.paramsP = {};
    $scope.paramsM = {};
    $scope.createPersonList = createPersonList;//新建个人
    $scope.createCompanyList = createCompanyList;//新建机构
    //$scope.addCustomerGroup = addCustomerGroup;
    $scope.addParams = {};

    function createPersonList() {
      $('body').find('.w5c-form .w5c-error').css('display','none')
      $scope.paramsP.customerGroupId = $scope.teamSelected;
      customerBarService.addZRRCustomer($scope.paramsP).then(function (data) {
        if(data.code==1){
          var item = {
            id: data.data.id,
            name: data.data.name,
            type : 1
          };
          $('#addPerson').modal('hide');
          $('#serName').val(data.data.name || '无');
          $('#pPhone').html(data.data.contactnumber);
          $('#pAddr').html(data.data.address || '无');
          $('#ppAddr').html(data.data.workplace || '无');
          // $scope.showPersonResult();
          $scope.paramsP = {};

          $scope.addPerList.push(item)
        }else{
          $scope.paramsP = {};

        }
      });
    }
    function createCompanyList() {
      $scope.paramsM.customerGroupId = $scope.teamSelected;
      customerBarService.addFRCustomer($scope.paramsM).then(function (data) {
        if(data.code == 1){
          var item = {
            id: data.data.customercompanyId,
            name: data.data.name,
            type : 2
          };
          $scope.personActive = 1;
          $('#addPerson').modal('hide');

            $('#serName').val(data.data.name);
            $('#cname').html(data.data.contactName);
            $('#cphone').html(data.data.phone || '无');
            $('#cAddress').html(data.data.address || '无');
            $scope.addPerList.push(item)

          $scope.paramsM = {};
        }
      });
    };

    document.onkeydown=function(e){
      var e = e || event;
      var currKey = e.keyCode || e.which || e.charCode;//支持IE,FireFox
      if (currKey == 13) {
        return false;
      }
    };


  };
  return newCase;
};
